using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Spike.ContractBuilder;

namespace Spike.TestHarness.Host
{
    public partial class HostControl : UserControl
    {
        public HostControl()
        {
            InitializeComponent();
        }

        private void AddEndpointControl(EndpointControl endCntrl)
        {
            TabPage page = new TabPage(endCntrl.Endpoint.Name);
            page.Controls.Add(endCntrl);
            cntrlEndpoints.TabPages.Add(page);
        }

        private string _serviceContract;

        public string ServiceHostContract
        {
            get { return _serviceContract; }
            set 
            { 
                _serviceContract = value;

                RefreshHostControl();
            }
        }

        private void RefreshHostControl()
        {
            ClearEndpointControls();
           
            foreach (ServiceHostEndpoint endpoint in ContractGenerator.Instance.Hosts[_serviceContract].GetEndpoints())
            {
                EndpointControl endCntrl = new EndpointControl();
                endCntrl.SetEndpoint(_serviceContract, endpoint);
                endCntrl.Dock = DockStyle.Fill;
                this.AddEndpointControl(endCntrl);
            }
        }

        public void ClearEndpointControls()
        {
            foreach (TabPage page in cntrlEndpoints.TabPages)
            {
                foreach (Control cntrl in page.Controls)
                    cntrl.Dispose();

                page.Dispose();
            }
        }



        private void btnGenerateHost_Click(object sender, EventArgs e)
        {
            List<string> errors = ContractGenerator.Instance.CreateStubService(_serviceContract + "Stub", _serviceContract);

            if (errors.Count != 0)
            {
                StringBuilder sb = new StringBuilder("Errors while creating the Stub:\r\n");
                foreach (string error in errors)
                    sb.Append("\t" + error + "\r\n");

                MessageBox.Show(sb.ToString(), "Stub Failure", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            ContractGenerator.Instance.ReloadAssemblies();
            ContractGenerator.Instance.LoadHost(_serviceContract);

            RefreshHostControl();
        }

    }
}
